package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User_Data;
import com.example.springboot.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 功能：
 * 作者：邓盛典
 * 日期：2024/8/25 7:56
 */
@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<Result> login(@RequestBody User_Data user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            return new ResponseEntity<>(Result.error("数据输入不合法"), HttpStatus.BAD_REQUEST);
        }
        try {
            User_Data dbUser = userService.login(user);
            if (dbUser!= null) {
                return new ResponseEntity<>(Result.success(true, dbUser), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Result.error("登录失败"), HttpStatus.UNAUTHORIZED);
            }
        } catch (RuntimeException e) {
            return new ResponseEntity<>(Result.error(e.getMessage()), HttpStatus.UNAUTHORIZED);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Result> register(@RequestBody User_Data user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            return new ResponseEntity<>(Result.error("数据输入不合法"), HttpStatus.BAD_REQUEST);
        }
        if (user.getUsername().length() > 10 || user.getPassword().length() > 20) {
            return new ResponseEntity<>(Result.error("数据输入不合法"), HttpStatus.BAD_REQUEST);
        }
        try {
            User_Data registeredUser = userService.register(user);
            return new ResponseEntity<>(Result.success(registeredUser), HttpStatus.CREATED);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(Result.error(e.getMessage()), HttpStatus.CONFLICT);
        }
    }
}